<template>
  <a-modal v-model:visible="visible" :footer="null" :title="$t('other.processTableInfo')" width="100%" wrap-class-name="large-modal" :maskClosable="false" :confirm-loading="loading" :keyboard="false">
    <a-spin :spinning="loading">
      <div class="make-process-modal-container">
        <aside>
          <a-row class="moinfo-box">
            <a-col :span="24" class="mb-8">
              <span>{{$t('hangManage.makeNo')}}：</span>
              <span>{{moInfo.moNo}} </span>
            </a-col>
            <a-col :span="24" class="mb-8">
              <span>{{$t('basicData.styleNo')}}：</span>
              <span>{{moInfo.styleNo}} </span>
            </a-col>
            <a-col :span="24">
              <span>{{$t('basicData.styleNa') }}：</span>
              <span>{{moInfo.styleName}} </span>
            </a-col>
          </a-row>
          <div class="px-20">
            <a-button type="primary" block @click="processAdd('add')">{{ $t('other.addVersion') }}</a-button>
          </div>
          <div class="choose-version-box">
            <div>
              <b>{{ getFieldText(versionList,processVersionId,'id','name') }}</b>
              <a-dropdown trigger="click">
                <span class="text-primary change-version"> {{ $t('other.toggle') }} </span>
                <template #overlay>
                  <a-menu v-if="versionList.length" class="header-line-menu">
                    <a-menu-item divided v-for="item in versionList" :key="item.id" @click="changeVersion(item.id )">
                      <span :class="processVersionId == item.id ? 'text-primary': ''"> {{item.name}}</span>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
            <div>
              <a-button type="warning1" size="small" :disabled="!versionList.length" @click="processAdd('edit')">{{ $t('common.editor') }}</a-button>
            </div>
          </div>
          <div class="version-box">
            <a-form :model="formState" ref="formRef" layout="vertical">
              <a-form-item :label="$t('basicData.processVerName')" :rules="processFormRule.name" name="name">
                <a-input v-model:value.trim="formState.name" :maxLength="19" disabled :placeholder="$t('common.pleaseInput')" />
              </a-form-item>
              <a-form-item :label="$t('common.effectDate')" name="effectiveDate" :rules="processFormRule.effectiveDate">
                <a-date-picker v-model:value="formState.effectiveDate" disabled class="full-width" value-format="YYYY-MM-DD" />
              </a-form-item>
              <a-form-item :label="$t('basicData.totalTime')" name="totalTime">
                <a-input-number v-model:value="formState.totalTime" disabled class="full-width">
                  <template #addonAfter> {{ $t('other.seconds') }} </template>
                </a-input-number>
              </a-form-item>
              <a-form-item :label="$t('basicData.totalPrice')" name="totalWages">
                <a-input-number v-model:value="formState.totalWages" disabled class="full-width">
                  <template #addonAfter> {{ $t('other.yuan') }} </template>
                </a-input-number>
              </a-form-item>
            </a-form>
          </div>
        </aside>
        <section>
          <ModalProcessList ref="processListRef" :styleId="moInfo.styleId" :loading="listLoading" :tableData="tableData" @workTimeChange="workTimeChange" @priceChange="priceChange" :processVersionId="processVersionId" :isView="true" :moId="moId" />
        </section>
      </div>
      <div class="modal-operate-btn">
        <a-button class="cancel" @click="onCancel">{{$t('common.cancel')}}</a-button>
      </div>
    </a-spin>
  </a-modal>

</template>
<script setup>
import { ref } from 'vue'
import { processFormRule } from './processConfig'
import ModalProcessList from './modalProcessList.vue'
import { message } from 'ant-design-vue'
import { getFieldText } from "@/utils"
import axios from "@/utils/request"
import moment from 'moment'
import i18n from '@/locales/index' 
const { t } = i18n.global
const emits = defineEmits(['operateProc'])
let loading = ref(false)
let visible = ref(false)
let listLoading = ref(false)
let moId = ref()  // 制单id
let moInfo = ref({})
let processVersionId = ref()
let processListRef = ref()
let tableData = ref([])
const formState = ref({})
let formRef = ref()
const versionList = ref([])
const open = async (record) => {
  visible.value = true
  loading.value = true
  try {
    moId.value = record.moId
    processVersionId.value = record.processId
    await getMakeInfo(moId.value)
    await getProcessList(moId.value)
    if (processVersionId.value) await getProcessDetails()
    loading.value = false
  } catch {
    loading.value = false
  }
}
const getMakeInfo = async (id) => { // 制单信息
  try {
    const res = await axios.getAction('/api/mo/mo/get', { id })
    moInfo.value = res.data || {}
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    moInfo.value = {}
  }
}
const initPage = (data) => {
  let { name, effectiveDate, moProcDetailVOList } = data
  moProcDetailVOList.forEach(i => {
    i.processPictureUrlList && i.processPictureUrlList.forEach((el) => {
      el.status = 'done'
      el.uid = Math.random()
    })
  })
  tableData.value = moProcDetailVOList
  formState.value = {
    name,
    effectiveDate: moment(effectiveDate ? effectiveDate : moment(new Date()).valueOf()).format('YYYY-MM-DD'),
    totalTime: tableData.value.reduce((prev, next) => { return prev + (next.standardSeconds || 0) }, 0).toFixed(8),
    totalWages: tableData.value.reduce((prev, next) => { return prev + (next.labourCost || 0) }, 0).toFixed(8)
  }
}
const getProcessList = async (id) => { // 工序版本列表
  try {
    const res = await axios.postAction('/api/mo/mo-proc/list', { moId: id })
    if (res.success) {
      versionList.value = res.data || []
      if (res.data.length && !processVersionId.value) {
        processVersionId.value = res.data[0].id
        getProcessDetails()
      }
    }
  } catch {
    message.warning(t('components.getDataErrorPleaseHolder'))
    versionList.value = []
  }
}
const changeVersion = (id) => {
  processVersionId.value = id
  getProcessDetails()
}
const getProcessDetails = async () => { // 工序详情
  listLoading.value = true
  try {
    const res = await axios.getAction('/api/mo/mo-proc/get', { id: processVersionId.value })
    if (res.success) {
      initPage(res.data)
    }
    listLoading.value = false
  } catch {
    listLoading.value = false
  }
}
const processAdd = async (type) => {
  emits('operateProc', type, { moId: moId.value, processId: processVersionId.value }, true)
  // visible.value = false
}
const workTimeChange = () => {
  formState.value.totalTime = processListRef.value.dataSource.reduce((prev, next) => { return prev + (next.standardSeconds || 0) }, 0).toFixed(8)
}
const priceChange = () => {
  formState.value.totalWages = processListRef.value.dataSource.reduce((prev, next) => { return prev + (next.labourCost || 0) }, 0).toFixed(8)
}
const onCancel = () => {
  visible.value = false
  visible.value = false
  formState.value = {}
  tableData.value = []
  moId.value = null
  versionList.value = []
  processVersionId.value = null
}
defineExpose({
  open,
  onCancel
})
</script>
